package Java_Lab.Multithreading.CycledThreads;

import java.util.Random;

public class Worker implements Runnable {
	
	private CyclicThreads pool;
	
	private Random rand = new Random();
	
	private String name;
	
	public Worker(String name, CyclicThreads pool) {
		this.pool = pool;
		this.name = name;
	}
	
	public String getName(){
		return name;
	}
	
	private int randInt(int min, int max){
		return rand.nextInt((max - min + 1)) + min;
	}
	
	public void run() {
		try{
			while(!Thread.interrupted()){
				synchronized (pool) {
					while(pool.currentWorker != this)
						pool.wait();

					System.out.println(name + " has been started");
					Thread.sleep(randInt(3000, 7000));
					System.out.println(name + " has been finished");
					pool.defineNext();
					pool.notifyAll();
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}
